/*
* 文件：FrameAnimation.cs
* 作者：王阳
* 时间：2019-5-20
* 描述：
*/
using UnityEngine;
using UnityEngine.UI;

namespace UnityX
{
    [DisallowMultipleComponent]
    [RequireComponent(typeof(RawImage))]
    [AddComponentMenu("UI/UnityX/FrameAnimation")]
    public class FrameAnimation : MonoBehaviour
    {
        public Texture2D[] images;
        public bool loop = true;
        public float fps = 60;
        public float duration
        {
            get
            {
                if (images == null || images.Length == 0)
                    return 0;
                return images.Length / fps;
            }
            set
            {
                if (images == null || images.Length == 0)
                    throw new System.Exception("duration设置失败，请先设置images！");
                if (value < 0.0001f)
                    return;
                fps = images.Length / value;
            }
        }

        private RawImage rawImage;
        private bool playing = false;
        private float startPlayTime;

        private void Awake()
        {
            rawImage = GetComponent<RawImage>();
        }
        private void Update()
        {
            if (playing)
            {
                int it = (int)((Time.time - startPlayTime) * fps);
                if (loop)
                {
                    rawImage.texture = images[it % images.Length];
                }
                else
                {
                    if (it >= images.Length)
                    {
                        rawImage.texture = images[images.Length - 1];
                        playing = false;
                    }
                    else
                    {
                        rawImage.texture = images[it];
                    }
                }
            }
        }
        public void Play()
        {
            if (images == null)
            {
                throw new System.Exception("Play失败，请先设置images！");
            }

            playing = true;
            startPlayTime = Time.time;
            if (rawImage == null)
            {
                rawImage = GetComponent<RawImage>();
            }
            rawImage.texture = images[0];
        }
        public void Stop()
        {
            playing = false;
        }
    }
}